package com.link.base.base.questionnairesurvey.service;

import com.link.base.base.questionnairesurvey.dao.mybatis.mapper.TopicMapper;
import com.link.base.base.questionnairesurvey.model.Answer;
import com.link.base.base.questionnairesurvey.model.Tab;
import com.link.base.base.questionnairesurvey.model.Topic;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 刘鲁
 * @date 2018-07-04
 * @comments 问卷主题服务
 */
@Service
public class TopicServiceImpl extends BasicServiceImpl<Topic> implements TopicService {

    @Resource
    private TopicMapper topicMapper;
    @Resource
    private TabService tabService;
    @Resource
    private AnswerService answerService;

    @Override
    public BasicMapper<Topic> getBasicMapper() {
        return topicMapper;
    }

    /**
     * 插入题目时插入选项
     *
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void afterInsert(Topic entity) throws Exception {

        List<Tab> list = entity.getTabList();
        if (!CollectionUtils.isEmpty(list)) {
            for (Tab arr : list) {
                arr.setTopicID(entity.getId().toString());
                tabService.insert(arr);
            }
        }
    }

    /**
     * 删除题目时删除选项
     *
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void beforDelete(Topic entity) throws Exception {
        //删除选项
        Tab tab = new Tab();
        tab.setPageFlag(false);
        tab.setTopicID(entity.getId().toString());
        List<Tab> tabList = tabService.queryByExamplePage(tab);
        for (Tab brr : tabList) {
            tabService.deleteById(brr);
        }
        //删除答案
        Answer answer = new Answer();
        answer.setPageFlag(false);
        answer.setTopicID(entity.getId());
        List<Answer> answerList = answerService.queryByExamplePage(answer);
        for (Answer brr : answerList) {
            answerService.deleteById(brr);
        }
    }

    @Override
    public void batchUpdateShowFlag(List<Topic> list) throws Exception {
        for (Topic topic : list) {
            checkId(topic);
            topicMapper.updateShowFlag(topic);
        }
    }

}
